package com.shiro.realm;

import com.shiro.POJO.User;
import com.shiro.Service.LoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@Component
public class UserRealm extends AuthorizingRealm {
    @Autowired
    //按照用户名查找到用户的数据库信息
    private LoginService loginService;
    @Override
    //用户的权限信息
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前登录主体
        Subject subject= SecurityUtils.getSubject();
        //获取用户信息
        User user= (User)subject.getPrincipal();
        //设置角色
        Set<String> roles=new HashSet<>();
        roles.add(user.getRoles());
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo(roles);
        //设置权限
        info.setStringPermissions(Collections.singleton(user.getPerms()));
        return info;
    }

    @Override
    //用户的角色信息
    //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //该参数就是shiro自动将用户提交的信息封装好的
        //第一步先拿到用户的Token,该Token包含用户的所有信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = loginService.login(token.getUsername());
        if (user == null) {
            System.out.println("不存在该用户");
        }
        else {
            //对比我从数据库里查出来的User对象的密码和Token里面的密码是否相等
            //getName()表示当前realm的名称,用于标识该认证信息的来源
            //这行代码会返回各种异常
            return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
        }
        return null;
    }
}
